package app.controllers.merchant;

import app.Const;
import app.interceptors.merchant.CommonInterceptor;
import app.models.booking.DiningRecord;
import app.models.sys.AuthUsers;
import app.models.sys.MerchantBrand;
import com.github.sog.controller.AjaxMessage;
import com.github.sog.controller.BasicController;
import com.github.sog.controller.security.SecurityKit;
import com.github.sog.libs.AppFunc;
import com.google.common.base.Strings;
import com.jfinal.aop.Before;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import org.joda.time.DateTime;

/**
 * <p>
 *     餐饮商户
 * </p>
 *
 * @author Jerry Ou
 * @version 1.0 2014-02-12 13:41
 * @since JDK 1.6
 */
@Before(CommonInterceptor.class)
public class RepastController extends BasicController {

    public void index() {
        String start_date = getPara("start_date");
        String end_date = getPara("end_date");

        String code = getPara("code");
        String phone = getPara("phone");
        int page = getParaToInt("page", 1);

        if (Strings.isNullOrEmpty(start_date)) {
            DateTime now = DateTime.now();
            start_date = now.toString(AppFunc.DATE_TIME_PATTERN_YYYY_MM_DD);
        }

        if (Strings.isNullOrEmpty(end_date)) {
            DateTime now = DateTime.now();
            end_date = now.toString(AppFunc.DATE_TIME_PATTERN_YYYY_MM_DD);
        }

        AuthUsers authUsers = SecurityKit.getLoginUser(getRequest());
        MerchantBrand brand = MerchantBrand.dao.findByMerchant(authUsers.getInt(AppFunc.TABLE_PK_COLUMN));
        Page<Record> recordPage = DiningRecord.dao.findByDateAndCodeAndPhone(start_date, end_date, code, phone, page, brand);
        setAttr("recordPage", recordPage);
        setAttr("bookings", recordPage.getList());
        setAttr("total", recordPage.getTotalPage());
        setAttr("start_date", start_date);
        setAttr("end_date", end_date);
        setAttr("code", code);
        setAttr("phone", phone);
        setAttr("page", page);
        render("index.ftl");
    }

    public void ok() {
        long booking_id = getParaToLong(0, 0l);
        if (booking_id == 0) {
            renderJson(AjaxMessage.nodata());
        } else {
            DiningRecord booking = DiningRecord.dao.findById(booking_id);
            booking.set(Const.COLUMN_STATUS, Const.BOOKING_STATUS.STATUS_2);
            final DateTime date = DateTime.now();
            booking.set("use_time", date.toDate());
            booking.update();
            renderSuccess(date.toString("yyyy-MM-dd HH:mm:ss"));
        }
    }
}
